<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>3D airport</title>
  <link rel="stylesheet" href="css/earth.css">
</head>
<body>
  <div id="WebGL-output"></div>
  <script src="js/three.js"></script>
  <script src="js/OrbitControls.js"></script>
  <script src="js/CSS2DRenderer.js"></script>
  <script src="js/dat.gui.min.js"></script>
  <script>
    var scene, camera, renderer
    var theEarth, airportTip
    // ===========  初始化场景  ========================
		function initScene() {
			scene = new THREE.Scene(); //场景构建
			// 构建一个坐标轴
			var axes = new THREE.AxisHelper(120);
			scene.add(axes);
		}

		// =========== 渲染器构建 ========================
		function initRenderer() {
			renderer = new THREE.WebGLRenderer({
				antialias: true, // 抗锯齿
				alpha: true // 背景透明
			}); //渲染器构建
			renderer.setClearAlpha(0); // 透明度为0
			renderer.setSize(window.innerWidth, window.innerHeight);
			renderer.shadowMapEnabled = true; //激活阴影
			document.querySelector("#WebGL-output").appendChild(renderer.domElement)
		}
    // ===============  初始化摄像头 ================
    function initCamera() {
      camera = new THREE.PerspectiveCamera(39, window.innerWidth / window.innerHeight, 0.1, 1000); //相机构建
      camera.position.x = 163;
      camera.position.y = 80;
      camera.position.z = -89;
      camera.lookAt(scene.position)
    }

    // ==================== 添加轨道控制器 =========================
    function initControl() {
      var orbitControls = new THREE.OrbitControls(camera, renderer.domElement);
      orbitControls.target = new THREE.Vector3(0, 0, 0) // 控制焦点
      orbitControls.autoRotate = false // 自动旋转关闭
      renderScene();

      function renderScene() {
        var clock = new THREE.Clock() // 用于更新轨道控制器
        var delta = clock.getDelta() // 获取时间差
        orbitControls.update(delta) // 更新时间
        requestAnimationFrame(renderScene);
      }
    }

    // ================== 灯光 =============================
		function initLights() {
			scene.add(new THREE.AmbientLight(0xFFFFFF));
		}


    // =================== 导入纹理 ================================
    function loadTexture(path){
      return new Promise((resolve, reject)=>{
        let loader = new THREE.TextureLoader();
        loader.load(path, texture => {
          resolve(texture);
        } , ()=>{} , ()=>{reject('fail')});
      });
    }

    // =================== 渲染地球 ================================
    function renderEarch() {
      var onProgress = function (process) {
			};
			var onError = function (err) {console.log(err)};
      let loader = new THREE.TextureLoader();
      loader.load('imgs/earth.jpg', texture => {
        let earthGeometry = new THREE.SphereGeometry( 60, 60, 60 );
        let earthMaterial = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
        theEarth = new THREE.Mesh( earthGeometry, earthMaterial );
        scene.add( theEarth );
      } , onProgress(), onError())

      // 机场位置
      var airportGeo = new THREE.PlaneBufferGeometry(4, 2, 1, 1)
			airportTip = new THREE.Mesh(airportGeo, createFont('某某机场', {bgColor: '#E6A23C', fontColor: '#FFFFFF'}))
      airportTip.position.set(-20, 30, -51)
      airportTip.rotation.y = 0
      airportTip.rotation.x = 16
      airportTip.rotation.z = 16
      scene.add(airportTip)
    }

    // var gui = new dat.GUI()
    // var controls = {
    //   rotationX: 16,
    //   rotationY: 0,
    //   rotationZ: 16,
    //   positionX: -20,
    //   positionY: 30,
    //   positionZ: -51
    // }
    // gui.add(controls, 'rotationX', 0, 20)
    // gui.add(controls, 'rotationY', 0, 20)
    // gui.add(controls, 'rotationZ', 0, 20)
    // gui.add(controls, 'positionX', -40, 0)
    // gui.add(controls, 'positionY', 30, 100)
    // gui.add(controls, 'positionZ', -100, 0)

    // ===================== 创建文字贴图 ======================
		/**
		 * text 文字
		 * options.fontColor 文字颜色
		 * options.bgColor 背景颜色
		 */
		function createFont (text, options={bgColor: '', fontColor: ''}) {
			var canvas = document.createElement("canvas");
			canvas.width = 512;
			canvas.height = 128;
			var c = canvas.getContext('2d');
			// 矩形区域填充背景
			c.fillStyle = options.bgColor || '#ff0000';
			c.fillRect(0, 0, 522, 128);
			c.beginPath();
			// 文字
			c.beginPath();
			c.translate(256,64);
			c.fillStyle = options.fontColor || '#ffffff'; //文本填充颜色
			c.font = 'bold 48px 微软雅黑'; //字体样式设置
			c.textBaseline = 'middle'; //文本与fillText定义的纵坐标
			c.textAlign = 'center'; //文本居中(以fillText定义的横坐标)
			c.fillText(text, 0, 0);
			var texture = new THREE.CanvasTexture(canvas);
			var textMaterial = new THREE.MeshPhongMaterial({
				map: texture, // 设置纹理贴图
				// side: THREE.DoubleSide,
				transparent: true,
				opacity: 0.9
			});
			textMaterial.map.needsUpdate = true
			return textMaterial
		}

    // ===================== 等比缩放 ==========================
		function handleWindowResize() {
			camera.aspect = window.innerWidth / window.innerHeight
			camera.updateProjectionMatrix()
			renderer.setSize(window.innerWidth, window.innerHeight)
		}


    // ===================== 动画 ======================
		function initAnimate() {
      renderer.render(scene, camera)
      if (theEarth) {
        theEarth.rotation.y += 0.05
        if (theEarth.rotation.y >= 4.7) {
          location.href = 'index.html'
        }
      }

      // 用于 dat.gui 调节位置
      // airportTip.rotation.x = controls.rotationX
      // airportTip.rotation.y = controls.rotationY
      // airportTip.rotation.z = controls.rotationZ

      // airportTip.position.x = controls.positionX
      // airportTip.position.y = controls.positionY
      // airportTip.position.z = controls.positionZ
			requestAnimationFrame(initAnimate)
		}


    function init() {
      initScene()
      initRenderer()
      initCamera()
      initControl()
      initLights()
      renderEarch()
      initAnimate()
      handleWindowResize()
      window.addEventListener('resize', handleWindowResize, false)
    }

    window.onload = function() {
      init()
    }

  </script>
</body>
</html>